package com.api.workflow.web;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.workflow.util.YNHttpUtils;

import io.swagger.v3.oas.annotations.parameters.RequestBody;

import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;

/**
 * 这个是给OA自己调用的
 */
@Path("/yn/oa")
public class OAYNWebController {
    public static void main(String[] args) {

    }

    /**
     * 接口： OA获取sap资产价值
     * 流程：资产减值申请
     *
     * @param requestBody JSON格式的请求体
     * @return
     */
    @POST
    @Path("/OAYNFII014")
    @Produces(MediaType.APPLICATION_JSON)
    public String OAYNFII014(@RequestBody String requestBody) {
        BaseBean baseBean = new BaseBean();
        RecordSet recordSet = new RecordSet();
        String message = "";
        try {
            JSONObject requestParams =  JSONObject.parseObject(requestBody);
            JSONObject object = new JSONObject();
            object.put("BUKRS", requestParams.getString("gsdm"));
            object.put("ANLN1", requestParams.getString("zcbh"));

            baseBean.writeLog("wyq==资产减值申请==========object" + object.toString());

            String post = YNHttpUtils.FII014(object.toString(), YNHttpUtils.token());

            baseBean.writeLog("wyq==资产减值申请==========post" + post);

            JSONObject jsonObject =  JSONObject.parseObject(post);
            baseBean.writeLog("wyq==资产减值申请==========jsonObject" + jsonObject.toString());

            String STATUS = jsonObject.getString("STATUS");
            String MESSAGE = jsonObject.getString("MESSAGE");

            JSONObject result = new JSONObject();
            result.put("status", STATUS);
            result.put("message", MESSAGE);

            if (STATUS.equals("S")) {
                JSONArray data = jsonObject.getJSONArray("DATA");
                baseBean.writeLog("wyq==资产减值申请==========data" + data.toString());

                JSONArray jsonArray = new JSONArray();

                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    JSONObject resultObject = new JSONObject();
                    resultObject.put("zcmc", jsonObject1.getString("TXT50"));
                    //resultObject.put("hjzz",jsonObject1.getString(""));
                    //resultObject.put("zjfw",jsonObject1.getString(""));
                    resultObject.put("ljzj", jsonObject1.getString("ZQMYZ"));
                    resultObject.put("jz", jsonObject1.getString("ZZMJZ"));
                    resultObject.put("syyf", jsonObject1.getString("ZSYYF"));
                    resultObject.put("ysyyf", jsonObject1.getString("ZZJYF"));
                    resultObject.put("sysyyf", jsonObject1.getString("ZZSYYF"));
                    resultObject.put("cbzx", jsonObject1.getString("KOSTL"));
                    resultObject.put("sb", jsonObject1.getString("EQUNR"));
                    Map<String, Object> resultObjectData = new HashMap<>();
                    Map<String, Object> insetMap = new HashMap<>();
                    insetMap.put("zckph", jsonObject1.getString("ANLN1"));

                    resultObjectData.put("zcmc", jsonObject1.getString("TXT50"));
                    resultObjectData.put("ljzj", jsonObject1.getString("ZQMZJ"));
                    resultObjectData.put("jz", jsonObject1.getString("ZZMJZ"));
                    resultObjectData.put("yz", jsonObject1.getString("ZQMYZ"));
                    resultObjectData.put("syyf", jsonObject1.getString("ZSYYF"));
                    resultObjectData.put("ysyyf", jsonObject1.getString("ZZJYF"));
                    resultObjectData.put("sysyyf", jsonObject1.getString("ZZSYYF"));
                    resultObjectData.put("cbzx", jsonObject1.getString("KOSTL"));
                    resultObjectData.put("zckph", jsonObject1.getString("ANLN1"));
                    resultObjectData.put("gsdm", requestParams.getString("gsdm"));
                    resultObjectData.put("gsdm1", requestParams.getString("gsdm"));
                    boolean equnr = requestParams.containsKey("EQUNR");
                    if (equnr) {
                        resultObjectData.put("sb", requestParams.get("EQUNR"));
                    }

                    recordSet.executeQuery("select count(*) as number from uf_zcxxbd where zckph =?", jsonObject1.getString("ANLN1"));
                    recordSet.next();
                    String number = Util.null2String(recordSet.getString("number"));
                    if (number.equals("0")) {
                        int modeId = getModeId("uf_zcxxbd");
                        boolean b = insetModeData("uf_zcxxbd", resultObjectData, 1, modeId);
                    } else {
                        boolean uf_djcgdd = updateModeData("uf_zcxxbd", resultObjectData, insetMap);
                        baseBean.writeLog("111==FII004=========修改" + uf_djcgdd);
                    }

                    baseBean.writeLog("wyq==资产减值申请============resultObject" + resultObject.toString());

                    jsonArray.add(resultObject);
                }
                result.put("data", jsonArray);
            }
            message = result.toString();
            baseBean.writeLog("wyq==资产减值申请============message" + message);

        } catch (Exception e) {
            baseBean.writeLog("wyq==资产减值申请=======exc" + e.toString());
            return e.toString();
        }

        return message;
    }

    /**
     * 接口：采购订单付款细腻系获取接口 12
     * 流程：OA-19 有订单预付款申请
     *
     * @param requestBody JSON格式的请求体
     * @return
     */
    @POST
    @Path("/OAYNFII004")
    @Produces(MediaType.APPLICATION_JSON)
    public String OAYNFII004(@RequestBody String requestBody) {
        BaseBean baseBean = new BaseBean();
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        try {
            JSONObject requestParams =  JSONObject.parseObject(requestBody);
            JSONObject object = new JSONObject();
            object.put("BUKRS", requestParams.getString("gsdm"));
            object.put("LIFNR", requestParams.getString("gys"));

            baseBean.writeLog("wyq==OAYNFII004=========object" + object.toString());

            String post = YNHttpUtils.FII004(object.toString(), YNHttpUtils.token());

            baseBean.writeLog("wyq==OAYNFII004=========post" + post);

            JSONObject jsonObject =  JSONObject.parseObject(post);

            String STATUS = jsonObject.getString("status");
            String MESSAGE = jsonObject.getString("message");

            if (STATUS.equals("S")) {
                JSONArray data = jsonObject.getJSONArray("data1");
                baseBean.writeLog("wyq==OAYNFII004=========data" + data.toString());

                RecordSet rs1 = new RecordSet();
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    String BUKRS = jsonObject1.getString("bukrs");
                    Map<String, Object> resultObject = new HashMap<>();
                    resultObject.put("ddlx", jsonObject1.getString("batxt"));
                    resultObject.put("zhfktj", jsonObject1.getString("zterm"));
                    resultObject.put("fktj", jsonObject1.getString("ratzt"));
                    resultObject.put("htje", jsonObject1.getString("brtwr"));
                    resultObject.put("fktjje", jsonObject1.getString("dmbtr"));
                    resultObject.put("yfljsqje", jsonObject1.getString("ljsq"));
                    resultObject.put("yjljfkje", jsonObject1.getString("ljfk"));
                    resultObject.put("bl", jsonObject1.getString("ratpz"));
                    resultObject.put("gsdm", requestParams.getString("gsdm"));
                    resultObject.put("gys", requestParams.getString("gys"));
                    resultObject.put("cgdd", jsonObject1.getString("ebeln"));
                    resultObject.put("wldm", jsonObject1.getString("matnr"));
                    resultObject.put("wlmc", jsonObject1.getString("maktx"));
                    resultObject.put("sl", jsonObject1.getString("menge"));
                    resultObject.put("dj", jsonObject1.getString("netpr"));
                    resultObject.put("ratzt", jsonObject1.getString("ratzt"));
                    resultObject.put("fktjms", jsonObject1.getString("ratztms"));
                    resultObject.put("zhfktjms", jsonObject1.getString("ztermms"));
                    resultObject.put("bz", jsonObject1.get("waers"));

                    resultObject.put("cgy", jsonObject1.getString("unsez"));

                    resultObject.put("zjxx", jsonObject1.getString("ebeln") + BUKRS + jsonObject1.getString("ratzt"));
                    baseBean.writeLog("wyq==OAYNFII004===========resultObject" + resultObject.toString());
                    Map<String, Object> insetMap = new HashMap<>();
                    insetMap.put("cgdd", jsonObject1.getString("ebeln"));
                    insetMap.put("gsdm", BUKRS);
                    insetMap.put("ratzt", jsonObject1.getString("ratzt"));
                    jsonArray.add(resultObject);
                    //查询数据库是否已存在
                    String select = "select count(*) as count from uf_djcgdd where cgdd = '" + jsonObject1.getString("ebeln") + "' and gsdm = '" + BUKRS + "' and ratzt='" + jsonObject1.getString("ratzt") + "'";
                    baseBean.writeLog("wyq==OAYNFII004===========select" + select);
                    rs1.execute(select);
                    if (rs1.next()) {
                        int count = rs1.getInt("count");
                        if (count == 0) {
                            //插入数据库
                            int modeId = getModeId("uf_djcgdd");
                            boolean b = insetModeData("uf_djcgdd", resultObject, 1, modeId);
                            baseBean.writeLog("wyq==FII004=========新增" + b);
                        } else {
                            boolean uf_djcgdd = updateModeData("uf_djcgdd", resultObject, insetMap);
                            baseBean.writeLog("wyq==FII004=========修改" + uf_djcgdd);
                        }
                    }


                }
            }
            result.put("status", STATUS);
            result.put("message", MESSAGE);
        } catch (Exception e) {
            result.put("status", "E");
            result.put("message", e.toString());
        }
        return result.toJSONString();
    }


    /**
     * 库存查询接口
     *
     * @param requestBody JSON格式的请求体
     * @return
     */
    @POST
    @Path("/OAYNMMI027")
    @Produces(MediaType.APPLICATION_JSON)
    public String OAYNMMI027(@RequestBody String requestBody) {
        BaseBean baseBean = new BaseBean();

        String message = "";
        try {
            JSONObject requestParams =  JSONObject.parseObject(requestBody);
            JSONObject object = new JSONObject();
            object.put("MATNR", requestParams.getString("MATNR"));
            object.put("WERKS", requestParams.getString("WERKS"));

            baseBean.writeLog("wyq==MMI027=========object" + object.toString());

            message = YNHttpUtils.MMI027(object.toString(), YNHttpUtils.token());

            baseBean.writeLog("wyq==MMI027=========post" + message);


        } catch (Exception e) {
            baseBean.writeLog("wyq==MMI027======exc" + e.toString());
            return e.toString();
        }


        return message;

    }


    /**
     * 功能位置查询接口
     *
     * @param requestBody JSON格式的请求体
     * @return
     */
    @POST
    @Path("/OAYNPMI003")
    @Produces(MediaType.APPLICATION_JSON)
    public String PMI003(@RequestBody String requestBody) {
        BaseBean baseBean = new BaseBean();
        String message = "";
        try {
            JSONObject requestParams =  JSONObject.parseObject(requestBody);
            JSONObject object = new JSONObject();

            object.put("IWERK", requestParams.getString("IWERK"));
            object.put("NAME1", requestParams.getString("NAME1"));
            object.put("TPLNR", requestParams.getString("TPLNR"));
            object.put("PLTXT", requestParams.getString("PLTXT"));
            baseBean.writeLog("wyq==PMI003=========object" + object.toString());
            message = YNHttpUtils.PMI003(object.toString(), YNHttpUtils.token());
            baseBean.writeLog("wyq==PMI003=========post" + message);
            JSONObject jsonPost =  JSONObject.parseObject(message);
            String STATUS = jsonPost.getString("STATUS");
            if ("S".equals(STATUS)) {
                JSONArray data = jsonPost.getJSONArray("DATA");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    RecordSet recordSet = new RecordSet();
                    int hrmResourceId = getModeId("uf_gnwz");
                    Map<String, Object> insetMap = new HashMap<>();
                    insetMap.put("gc", jsonObject1.getString("IWERK"));
                    insetMap.put("gcmc", jsonObject1.getString("NAME1"));
                    insetMap.put("gnwz", jsonObject1.getString("TPLNR"));
                    insetMap.put("gnwzms", jsonObject1.getString("PLTXT"));
                    new BaseBean().writeLog("insetMapinsetMapinsetMap" + insetMap);
                    recordSet.executeQuery("select count(*) as number from uf_gnwz where gc=? and gnwz=?", jsonObject1.getString("IWERK"), jsonObject1.getString("TPLNR"));
                    recordSet.next();
                    String counts = Util.null2String(recordSet.getString("number"));
                    new BaseBean().writeLog("countscounts" + counts);
                    if (counts.equals("0")) {
                        insetModeData("uf_gnwz", insetMap, 1, hrmResourceId);
                        new BaseBean().writeLog("insert---end");
                    } else {
                        recordSet.executeUpdate("update uf_gnwz set gcmc=?,gnwzms=? where gc=? and gnwz=?", requestParams.getString("NAME1"), requestParams.getString("PLTXT"), requestParams.getString("IWERK"), requestParams.getString("TPLNR"));
                        new BaseBean().writeLog("updateupdateupdate---end");
                    }

                }
            }

        } catch (Exception e) {
            baseBean.writeLog("wyq==PMI003======exc" + e.toString());
            return e.toString();
        }

        return message;

    }


    /**
     * 拉取应付
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/pullAccountsPayable")
    @Produces(MediaType.TEXT_PLAIN)
    public String pullAccountsPayable(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        com.weaver.general.BaseBean baseBean = new com.weaver.general.BaseBean();
        Map<String, Object> objectObjectHashMap1 = new HashMap<>();
        try {
            Date date = DateUtil.date();
            String format = DateUtil.format(date, "yyyyMMdd");
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("CPUDT", format);
            baseBean.writeLog("wyq==pullAccountsPayable==========jsonObject" + jsonObject.toString());
            String post = YNHttpUtils.FII010(jsonObject.toString(), YNHttpUtils.token());
            baseBean.writeLog("wyq==pullAccountsPayable==========post" + post);


            JSONObject jsonPOST =  JSONObject.parseObject(post);
            String STATUS = jsonPOST.getString("STATUS");
            String MESSAGE = jsonPOST.getString("MESSAGE");

            if ("S".equals(STATUS)) {
                RecordSet rs1 = new RecordSet();
                JSONArray data = jsonPOST.getJSONArray("DATA");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    //查询数据库是否已存在
                    String select = "select * from uf_yfzkbd where gsdm = '" + jsonObject1.getString("BUKRS") + "' and"
                            + " hjnd = '" + jsonObject1.getString("GJAHR") + "' and"
                            + " hjpzdpzbh = '" + jsonObject1.getString("BELNR") + "' and"
                            + " hjpzzdxxmbh = '" + jsonObject1.getString("BUZEI") + "'";

                    baseBean.writeLog("wyq==pullAccountsPayable==========select" + select);

                    boolean b1 = rs1.execute(select);
                    baseBean.writeLog("wyq==pullAccountsPayable==========b1" + b1);

                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("gsdm", jsonObject1.getString("BUKRS"));
                    objectObjectHashMap.put("gyskmbm", jsonObject1.getString("LIFNR"));
                    objectObjectHashMap.put("fpbh", jsonObject1.getString("ZUONR"));
                    objectObjectHashMap.put("hjnd", jsonObject1.getString("GJAHR"));
                    objectObjectHashMap.put("hjpzdpzbh", jsonObject1.getString("BELNR"));
                    objectObjectHashMap.put("hjpzzdxxmbh", jsonObject1.getString("BUZEI"));
                    objectObjectHashMap.put("bz", jsonObject1.getString("WAERS"));
                    objectObjectHashMap.put("fktjbm", jsonObject1.getString("ZTERM"));
                    objectObjectHashMap.put("zftjdms", jsonObject1.getString("ZTERMMS"));
                    objectObjectHashMap.put("pzhbje", jsonObject1.getString("WRBTR"));
                    objectObjectHashMap.put("lrzx", jsonObject1.getString("PRCTR"));
                    objectObjectHashMap.put("zzhth", jsonObject1.getString("ZZ005"));
                    objectObjectHashMap.put("cgy", jsonObject1.getString("UNSEZ"));
                    String wybs = jsonObject1.getString("BUKRS") + jsonObject1.getString("GJAHR") + jsonObject1.getString("BELNR") + jsonObject1.getString("BUZEI");
                    objectObjectHashMap.put("wybs", wybs);//唯一标识
                    rs1.next();
                    int counts = rs1.getCounts();
                    if (counts == 0) {
                        //插入数据库
                        int modeId = getModeId("uf_yfzkbd");
                        boolean b2 = insetModeData1("uf_yfzkbd", objectObjectHashMap, 1, modeId);
                        baseBean.writeLog("wyq==pullAccountsPayable=========插入" + b2);
                    } else {
                        //更新数据库
                        Map<String, Object> whereMap = new HashMap<>();
                        whereMap.put("gsdm", objectObjectHashMap.get("gsdm"));
                        whereMap.put("hjnd", objectObjectHashMap.get("hjnd"));
                        whereMap.put("hjpzdpzbh", objectObjectHashMap.get("hjpzdpzbh"));
                        whereMap.put("hjpzzdxxmbh", objectObjectHashMap.get("hjpzzdxxmbh"));
                        boolean b2 = updateModeData1("uf_yfzkbd", objectObjectHashMap, whereMap);
                        baseBean.writeLog("wyq==pullAccountsPayable=========更新" + b2);

                    }
                }
            } else {
                objectObjectHashMap1.put("status", 0);
                objectObjectHashMap1.put("message", MESSAGE);
            }
        } catch (Exception e) {
            baseBean.writeLog("wyq==pullAccountsPayable==========Exception" + e.toString());
        }
        objectObjectHashMap1.put("status", 1);
        return com.alibaba.fastjson.JSONObject.toJSONString(objectObjectHashMap1);
    }

    public static boolean insetModeData1(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value != null && !value.equals("")) {
                columns += (key + ",");
                values += ("?,");
                dataList.add(value);
            }

        }
        BaseBean baseBean = new BaseBean();
        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        baseBean.writeLog("===========insertSql", insertSql);
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }


    public static boolean updateModeData1(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null || value.equals("")) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }


    /**
     * 插入到建模表数据
     *
     * @param tableName
     * @param data
     * @param hrmResourceId
     * @param modeId
     * @return
     * @throws Exception
     */
    public static boolean insetModeData(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            columns += (key + ",");
            values += ("?,");
            dataList.add(value);
        }

        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        new BaseBean().writeLog("insertSql", insertSql);
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }

    /**
     * @param tablename
     * @return
     */
    public static int getModeId(String tablename) {
        RecordSet rs = new RecordSet();
        Map<String, Integer> map = new HashMap<>();
        rs.executeQuery("select b.tablename,a.formid,b.detailkeyfield,a.id from modeinfo a,workflow_bill b where a.formid = b.id  and tablename=?", tablename);
        if (rs.next()) {
            int id = rs.getInt("id");
            return id;
        }
        return 0;
    }


    public static boolean updateModeData(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }

    /**
     * 接口： 查询_客户销售数据同步(外围系统->SAP)
     * 流程：
     *
     * @param requestBody JSON格式的请求体
     * @return
     */
    @POST
    @Path("/OASDI011")
    @Produces(MediaType.APPLICATION_JSON)
    public String OASDI011(@RequestBody String requestBody) {
        BaseBean baseBean = new BaseBean();
        RecordSet recordSet = new RecordSet();
        String message = "";
        try {
            JSONObject requestParams =  JSONObject.parseObject(requestBody);
            JSONObject object = new JSONObject();
            object.put("AEDAT", requestParams.getString("AEDAT")); // 查询申请日期
            object.put("KUNAG", requestParams.getString("KUNAG")); // 客户编码
            object.put("ZXYD", requestParams.getString("ZXYD")); // 信用段
            object.put("WERKS", requestParams.getString("WERKS")); // 工厂
            object.put("LGORT", requestParams.getString("LGORT")); // 存储地点
            String MATNR_LIST = requestParams.getString("MATNR_LIST");
            JSONArray jsonObject1 =  JSONArray.parseArray(MATNR_LIST);
            object.put("MATNR_LIST", jsonObject1); // 物料列表

            baseBean.writeLog("lcm==客户销售数据==========object" + object.toString());

            String post = YNHttpUtils.SDI011(object.toString(), YNHttpUtils.token());

            baseBean.writeLog("lcm==客户销售数据==========post" + post);

            JSONObject jsonObject =  JSONObject.parseObject( post);
            baseBean.writeLog("lcm==客户销售数据==========jsonObject" + jsonObject.toString());

//            String STATUS = jsonObject.getString("STATUS");
//            String MESSAGE = jsonObject.getString("MESSAGE");

            JSONObject result = new JSONObject();
//            result.put("status", STATUS);
//            result.put("message", MESSAGE);

//            if (STATUS.equals("S")) {
//                JSONObject data = jsonObject.getJSONObject("DATA");
            result.put("data", post);
//            }
            message = result.toString();
            baseBean.writeLog("lcm==客户销售数据============message" + message);

        } catch (Exception e) {
            baseBean.writeLog("lcm==客户销售数据=======exc" + e.toString());
            return e.toString();
        }
        return message;
    }

}